package fun.codedesign.principle.advice151.a129;

import java.util.Calendar;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockTemplate {

    public static void main(String[] args) {
        ExecutorService service = Executors.newFixedThreadPool(3);
        for (int i = 0; i < 3; i++) {
            service.submit(new LockTask()); // 没有互斥，lock为私有变量所以没有互斥
            //service.submit(new SyncTask()); // 互斥
        }
        service.shutdown();
        System.out.println(service.isShutdown());
    }


}

class SyncTask implements Runnable {

    @Override
    public void run() {
        synchronized ("A") {
            try {
                Thread.sleep(5000);
                System.out.println("运行时间：" + Calendar.getInstance().get(Calendar.SECOND));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class LockTask implements Runnable {

    private Lock lock = new ReentrantLock();

    @Override
    public void run() {
        try {
            lock.lock();
            Thread.sleep(5000);
            System.out.println("hello kitty" + "运行时间：" + Calendar.getInstance().get(Calendar.SECOND));
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
